package com.laiketui.plugin.common.service;

import com.laiketui.plugin.common.domain.base.IntegralConfigModel;
import com.laiketui.plugin.common.domain.base.SignRecordModel;
import com.laiketui.plugin.common.domain.lktconst.DictionaryConst;
import com.laiketui.plugin.common.domain.lktconst.ErrorCode;
import com.laiketui.plugin.common.domain.vo.integral.AddScoreVo;
import com.laiketui.plugin.common.interfaces.PublicIntegralService;
import com.laiketui.plugin.common.mapper.IntegralConfigModelMapper;
import com.laiketui.plugin.common.mapper.SignRecordModelMapper;
import com.laiketui.plugin.common.mapper.UserMapper;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.utils.tool.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;


/**
 * 积分相关
 *
 * @author Trick
 * @date 2021/11/9 17:48
 */
@Service
public class PublicIntegralServiceImpl implements PublicIntegralService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SignRecordModelMapper signRecordModelMapper;

    @Autowired
    private IntegralConfigModelMapper integralConfigModelMapper;

    @Override
    public void addScore(AddScoreVo vo) throws LaiKeAPIException {
        try {
            String event = vo.getEvent();
            SignRecordModel signRecordModel = new SignRecordModel();
            signRecordModel.setStore_id(vo.getStoreId());
            signRecordModel.setUser_id(vo.getUserId());
            signRecordModel.setSign_score(vo.getScore());
            signRecordModel.setTotal_score(vo.getScoreOld());
            signRecordModel.setRecord(event);
            signRecordModel.setType(vo.getType());
            signRecordModel.setsNo(vo.getOrderNo());
            signRecordModel.setScore_invalid(vo.getScoreInvalidDate());
            signRecordModel.setSign_time(new Date());
            signRecordModel.setFrozen_time(vo.getFrozenTime());
            signRecordModelMapper.insertSelective(signRecordModel);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("记录增减积分流水 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "addScore");
        }
    }

    @Override
    public void giveScore(int storeId, String userId, String orderNo, BigDecimal orderPrice, int userScore, int type) throws LaiKeAPIException {
        try {
            //积分确认收货获取积分
            IntegralConfigModel integralConfigModel = new IntegralConfigModel();
            integralConfigModel.setStore_id(storeId);
            integralConfigModel = integralConfigModelMapper.selectOne(integralConfigModel);
            if (integralConfigModel != null && integralConfigModel.getStatus() == 1 && integralConfigModel.getGive_status() == type) {
                AddScoreVo scoreVo = new AddScoreVo();
                scoreVo.setStoreId(storeId);
                scoreVo.setUserId(userId);
                scoreVo.setScoreOld(userScore);
                scoreVo.setType(DictionaryConst.IntegralType.SHOP_INTEGRAL);
                scoreVo.setOrderNo(orderNo);
                //计算所得积分 购物赠送积分=购物交易金额*赠送比例
                BigDecimal score = orderPrice.multiply(integralConfigModel.getProportion()).divide(new BigDecimal("100"), 0, BigDecimal.ROUND_UP);
                if (score.compareTo(BigDecimal.ZERO) > 0) {
                    //积分过期时间
                    Date scoreInvalidDate = null;
                    if (integralConfigModel.getOverdue_time() != null && integralConfigModel.getOverdue_time() > 0) {
                        scoreInvalidDate = DateUtil.getAddDateBySecond(new Date(), integralConfigModel.getOverdue_time());
                    }
                    String event = "";
                    if (integralConfigModel.getGive_status() == 0) {
                        event = userId + " 确认收货积分商品获取了" + score + "积分";
                    } else {
                        event = userId + " 支付积分商品获取了" + score + "积分";
                    }
                    scoreVo.setScore(score.intValue());
                    scoreVo.setEvent(event);
                    scoreVo.setScoreInvalidDate(scoreInvalidDate);
                    this.addScore(scoreVo);
                    int row = userMapper.updateUserScore(score.intValue(), storeId, userId);
                    if (row < 0) {
                        logger.debug("{} 购物赠送积分失败", event);
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CZSB, "操作失败", "giveScore");
                    }
                }
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("赠送积分 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "giveScore");
        }
    }
}

